package utils

import (
	"game-server/manager"
	"game-server/model"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/gorilla/websocket"
)

var (
	// 配置websocket升级器
	upgrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true // 允许所有来源，生产环境应该配置具体的允许来源
		},
	}

	// 工作池实例 - 处理客户端连接
	workerPool = NewWorkerPool(15)
)

// GlobalWorkerPool 全局工作池实例，用于外部访问
var GlobalWorkerPool = workerPool

// 初始化函数，设置全局依赖
func init() {
	// 注入依赖
	model.GlobalClientManager = manager.GlobalClientManager
	model.GlobalRouter = manager.GlobalRouter
}

// HandleWebSocket 处理WebSocket连接
func HandleWebSocket(c *gin.Context) {
	// 从上下文中获取JWT claims
	claims, exists := c.Get("claims")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "未授权"})
		return
	}
	jwtClaims := claims.(jwt.MapClaims)

	// 从claims中获取用户信息
	userID := uint(jwtClaims["user_id"].(float64))
	username := jwtClaims["username"].(string)

	// 升级HTTP连接为WebSocket连接
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Printf("WebSocket升级失败: %v", err)
		return
	}

	// 创建新的客户端
	client := &model.Client{
		ID:       userID,
		Username: username,
		Conn:     conn,
		Send:     make(chan []byte, 256),
	}

	// 将新客户端添加到clients map
	manager.GlobalClientManager.AddClient(userID, client)

	log.Printf("用户 %s (ID: %d) 已连接", username, userID)

	// 提交到工作池处理
	workerPool.Submit(client)
}
